<script lang="ts" setup>
import { ref, computed, h, watch } from 'vue'
import { AliwangwangOutlined, RedoOutlined } from '@ant-design/icons-vue'
import { useI18n } from 'vue-i18n'
import ColumnSetting from '@/components/Table/src/components/settings/ColumnSetting.vue'
import { useColumn } from '@/components/Table/src/hooks/useColumn'
import { BasicPageParams, BasicTableColumn } from '@/types'
import { User } from '@/types/modules/user'
import { genderOptions } from '@/types/modules/gender'
import { cloneDeep } from 'lodash-es'
import { isEmpty, isArray, isObject } from '@/utils/is'

import * as authApi from './api-multi-factor-authorization'
import * as signalR from '@/api/modules/interactive'

import { SecurityScanOutlined } from '@ant-design/icons-vue';
import { message, notification } from 'ant-design-vue'

import authCallbackModule from '@/views/temporary-authorization/components/toast-auth-callback.vue'
import { TYPE, useToast } from 'vue-toastification'
const toast = useToast()

const { t } = useI18n()
const props = defineProps({
  title: { type: String, default: () => 'Default Title' },
  columns: { type: Array<BasicTableColumn>, default: () => [] },
  tableData: { type: Array, default: () => [] },
  total: { type: Number, default: () => 0 },
  pageParams: { type: Object as PropType<BasicPageParams>, default: () => { } },
  syncStatus: { type: Boolean, default: () => false }
})
const emit = defineEmits(['add', 'refresh', 'check'])

const {
  indexColumnChecked,
  indexColumnData,
  actionsColumnData,
  selectColumnData,
  onChangeSelectColumn
} = useColumn<User>(props.pageParams)
const sortColumns = ref(cloneDeep(props.columns))

const tableColumns = computed(() => {
  let showColumns = sortColumns.value.filter(
    (item: BasicTableColumn) => item.checked
  )
  const indexColumn = indexColumnChecked.value ? [indexColumnData] : []
  return [...indexColumn, ...showColumns, actionsColumnData]
})

const resetColumn = () => {
  sortColumns.value = props.columns.map(item => {
    item.checked = true
    item.fixed = false
    return item
  })
  onChangeSelectColumn(false)
}

const taskId = ref<string>()
const code = ref<string>()
const two_factor_visbile = ref<boolean>(false)
const submitAuth = (row: any) => {
  two_factor_visbile.value = true;
  signalR.default.attachToHub('UserSensitiveDataTemporaryAuthorizationCallback', (record: any) => {
    if (record.data.status == 0) {
      toast({
        component: authCallbackModule,
        props: {
          context: record
        },
        listeners: {
          crop: () => {
            code.value = record.data.code            
            toast.update('user-temp-auth-callback', { content: '流程结束', options: { timeout: 2000, type: TYPE.SUCCESS } })
          }
        }
      }, {
        id: 'user-temp-auth-callback'
      })
    } else {
      two_factor_visbile.value = false;
      toast(record.data.description, { timeout: 5000, type: TYPE.ERROR })
    }
  });

  authApi.tryAcquireAsync(row.account, `申请查看工号为${row.jobNumber}的用户的姓名`).then(res => {
    taskId.value = res as unknown as string;
  })
}

const afterClose = () => {
  signalR.default.detachFromHub('UserSensitiveDataTemporaryAuthorizationCallback')
  toast.dismiss('user-temp-auth-callback')
  taskId.value = '';
  code.value = '';
}

const verifyCode = () => {
  authApi.getAuthData(taskId.value as string, code.value as string).then(res => {
    if (res.status != 0) {
      message.error(res.message)
    }
    else {
      let idx = props.tableData.findIndex((x: User) => x.account == res.data.account)
      props.tableData[idx] = res.data;
      taskId.value = '';
      code.value = '';
      two_factor_visbile.value = false;
    }
  })  
}

watch(two_factor_visbile, (newValue) => {
  if (newValue) {
    toast('已发送临时授权申请', { timeout: 2000, type: TYPE.SUCCESS })
  }
  
})
</script>
<template>
  <div class="table-list">
    <a-col :span="24" class="table-title">
      <h3>{{ props.title }}</h3>
      <div class="operate">        
        <a-divider type="vertical" />
        <a-tooltip class="operate-icon">
          <span class="refresh">
            <redo-outlined @click="emit('refresh')" />
          </span>
          <template #title> {{ t('system.refresh') }} </template>
        </a-tooltip>

        <column-setting v-model:checked="indexColumnChecked" v-bind="{ sortColumns, columns }"
          @change-select="onChangeSelectColumn" @reset="resetColumn" />
      </div>
    </a-col>

    <a-table :columns="tableColumns" :rowKey="(record: User) => record.id" :row-selection="selectColumnData"
      :data-source="tableData" :scroll="{ x: 1000 }" class="ant-table-striped" :row-class-name="
        (_record: User, index: number) => (index % 2 === 1 ? 'table-striped' : null)
      " :pagination="false" bordered>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'actions'">
          <slot name="operate" v-bind="record"></slot>
        </template>
        <template v-if="column.dataIndex === 'name'">
          <span style="margin-right: 8px;">{{ record[column.dataIndex] }}</span>
          <div style="cursor: pointer; color: #00e952; display: inline-block; font-size: 1.1em;">
            <a-tooltip>
              <template #title>点击申请授权查看敏感数据</template>
              <SecurityScanOutlined @click="submitAuth(record)"/>
            </a-tooltip>
          </div>
        </template>

        <template
          v-else-if="(isEmpty(record[column.dataIndex]) && !isObject(record[column.dataIndex]) && !column.isCheck)">
          <a-typography-text type="secondary">-</a-typography-text>
        </template>

        <template v-if="column.isCheck">
          <div v-if="isArray(record[column.dataIndex])" class="ap-table-list-tags">
            <div v-if="!isEmpty(record[column.dataIndex])">
              <a-tag color="cyan" v-for="(item, idx) in record[column.dataIndex]" :key="idx">
                <a @click="emit('check', column.dataIndex, item[column.name], item)">
                  {{ item[column.name] }}
                </a>
              </a-tag>
            </div>
            <a-typography-text v-else type="secondary">
              <a-typography-text type="secondary">-</a-typography-text>
            </a-typography-text>
          </div>
          <a-button v-else-if="isObject(record[column.dataIndex])" type="link" style="padding: 0" @click="
            emit(
              'check',
              column.dataIndex,
              record[column.dataIndex][column.name],
              record[column.dataIndex]
            )
          ">
            {{ record[column.dataIndex][column.name] }}
          </a-button>
          <a-typography-text v-else type="secondary">
            <a-typography-text type="secondary">-</a-typography-text>
          </a-typography-text>
        </template>

        <template v-else>
        </template>
      </template>
    </a-table>
    <a-col class="table-pagination" :span="24">
      <a-pagination show-size-changer v-model:current="pageParams.pageNum" v-model:page-size="pageParams.pageSize"
        :page-size-options="['10', '20', '30']" :total="props.total"
        :show-total="(total: number) => `${t('system.pagination.start')} ${total} ${t('system.pagination.end')}`"
        @change="emit('refresh')" />
    </a-col>

    <a-modal ref="modalRef" v-model:visible="two_factor_visbile" :wrap-style="{ overflow: 'hidden' }" style="width: 400px;"
      :closable="false" :keyboard="false" :maskClosable="false" :afterClose="afterClose" :destroyOnClose="true" @ok="verifyCode">      
      <div>
        <span>请输入授权码：</span>
        <a-input v-model:value="code"></a-input>
      </div>
      <template #title>
        <div ref="modalTitleRef" style="width: 100%; cursor: auto">申请临时授权</div>
      </template>      
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
.table-list {
  .table-title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;

    .operate {
      display: flex;
      align-items: center;

      .operate-icon {
        margin-right: 12px;

        &.anticon,
        & .anticon {
          font-size: 20px;
        }
      }
    }
  }

  .table-pagination {
    text-align: right;
    margin-top: 20px;
  }
}
</style>
